package org.ycx.upms.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.upms.dao.enmus.BaseState;
import org.ycx.upms.dao.model.*;
import org.ycx.upms.service.ISecGroupService;
import org.ycx.upms.service.ISecRoleService;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SecGroupcontroller
 * Created by yang on 2017-07-19 16:25:40.
 */
@Controller
@RequestMapping("/sec/group")
public class SecGroupController {

    private static Logger _log = LoggerFactory.getLogger(SecGroupController.class);

    private static final String PRE = "sec/group/";

    @Autowired
    private ISecGroupService service;

    @Autowired
    private ISecRoleService roleService;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
        return PRE + "create";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        SecGroup bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean", bean);
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        SecGroup bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean", bean);
        return PRE + "detail";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(SecGroup bean, HttpSession session) {
        ComplexResult result = FluentValidator.checkAll()
                .on(bean.getGroupName(), new NotNullValidator("用户组名称"))
                .on(bean.getgDesc(), new NotNullValidator("用户组描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(), "\n\r"));
            return error;
        }
        int count = service.insertSelective(bean);
        return new RespMSG(RespCode.SUCCESS);
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, SecGroup bean, HttpSession session) {
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll()
                .on(bean.getGroupName(), new NotNullValidator("用户组名称"))
                .on(bean.getgDesc(), new NotNullValidator("用户组描述"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(), "\n\r"));
            return error;
        }
        int count = service.updateByPrimaryKeySelective(bean);
        return new RespMSG(RespCode.SUCCESS);
    }

    @RequestMapping("/role.html")
    public String rolesPage(Integer gid, ModelMap ui) {
        SecRoleExample sre = new SecRoleExample();
        sre.createCriteria().andRoleStateEqualTo(BaseState.MALE.getKey() + "");
        List<SecRole> roles = roleService.selectByExample(sre);
        List<Integer> rids = this.service.selectRidsByGid(gid);
        SecGroup user = this.service.selectByPrimaryKey(gid);
        ui.put("roles", roles);
        ui.put("rids", rids);
        ui.put("user", user);
        return PRE + "roles";
    }

    @RequestMapping("/role")
    @ResponseBody
    public RespMSG grantRole(Integer uid, Integer rids[]) {
        int res = 0;
        res = this.service.updateGroupRole(uid, rids);
        RespMSG msg = new RespMSG(RespCode.SUCCESS);
        msg.setData(res);
        return msg;
    }

    /**
     * 用户页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/users.html")
    public String usersPage(ModelMap modelMap) {
        return PRE + "users";
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG delete(@PathVariable("ids") String ids) {
        int count = service.deleteByPrimaryKeys(ids);
        return new RespMSG(RespCode.SUCCESS);
    }

    @RequestMapping("/user")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = true, value = "gid") Integer gid) {
        //TODO 模糊查询定义
        List<SecUser> rows = service.selectByGroup(gid,offset, limit);
        long total = service.countByGroup(gid);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        SecGroupExample beanExample = new SecGroupExample();
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            beanExample.setOrderByClause(sort + " " + order);
        }
        //TODO 模糊查询定义
        List<SecGroup> rows = service.selectByExampleForOffsetPage(beanExample, offset, limit);
        long total = service.countByExample(beanExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }
}
